package raft

import (
	"math/rand"
	"time"
)

//need called when hold rf.mu
//check if other's term is bigger than mine
func (rf *Raft) handleOthersTerm(term int) (ans bool) {
	if term > rf.persistentContext.CurrentTerm {
		rf.changeToState(FollowerState, term)
		ans = true
		return
	}
	ans = false
	return
}

func (rf *Raft) resetTimeoutClock() {
	rf.clockMu.Lock()
	defer rf.clockMu.Unlock()

	t := int64(TimeoutBase) + rand.Int63n(int64(TimeoutRange))
	rf.timeoutStamp = time.Now().UnixMilli() + t

}

func (rf *Raft) getLastLogTerm() int {

	return rf.persistentContext.GetEntryTerm(rf.persistentContext.GetLastIndex())
}

/*
//need called when hold rf.mu
func (rf *Raft) sendAndWait(sendfunc func(int, chan int) error, recfunc func(int) bool) {
	cnt := len(rf.peers) - 1
	chn := make(chan int, cnt)
	for i, _ := range rf.peers {
		if i == rf.me {
			continue
		}
		go func(v int) {
			if sendfunc(v, chn) != nil {
				chn <- 0
			}
		}(i)
	}
	go func() {
		i := 0
		for b := range chn {
			if rf.killed() {
				break
			}
			i++
			if !recfunc(b) {
				break
			}
			if cnt == i {
				break
			}
		}
		rf.mu.Lock()
		rf.Log("INFO", "recv from all others")
		rf.mu.Unlock()
	}()
}*/
